﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace LEShortcut.Helper
{
    internal static class UpdateHelper
    {
        private const string VerPattern = @"(?:v|ver|Ver|VER)\s*\d+.\d+.\d+.\d+";
        private const string VerInfoPattern = @"\d+.\d+.\d+.\d+";

        internal static bool CheckUpdate(ref Version version)
        {
            try
            {
                //Load download feed from codeplex
                XDocument xdoc =
                    XDocument.Load(
                        "http://leshortcut.codeplex.com/project/feeds/rss?ProjectRSSFeed=codeplex%3a%2f%2frelease%2fleshortcut");
                //Get first release item from feed xml
                XElement query =
                    xdoc.Elements("rss")
                        .First()
                        .Elements("channel")
                        .First()
                        .Elements("item")
                        .First(m =>
                        {
                            XElement xElement = m.Element("title");
                            return xElement != null && (xElement.Value.StartsWith("Released:"));
                        });
                // ReSharper disable once PossibleNullReferenceException
                string title = query.Element("title").Value.ToLower();
                Match match = Regex.Match(title, VerPattern);
                string verinfo = Regex.Match(match.Value, VerInfoPattern).Value;
                var newVer = new Version(verinfo);
                var curVer =
                    new Version(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion);
                if (newVer > curVer)
                {
                    version = newVer;
                    return true;
                }
            }
// ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }
            return false;
        }
    }
}